package com.sanri.tools.modules.mock.l7.http.service;

import com.alibaba.fastjson.JSON;
import com.sanri.tools.modules.core.dtos.PageResponseDto;
import com.sanri.tools.modules.core.service.file.FileManager;
import com.sanri.tools.modules.mock.l7.http.service.dtos.RequestLog;
import com.sanri.tools.modules.mock.l7.http.service.dtos.RequestLogDto;
import com.sanri.tools.modules.mock.l7.http.service.dtos.ResponseConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class LogService {
    @Autowired
    private FileManager fileManager;

    private YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader();

    /**
     * 列出请求列表
     * @return
     * @throws IOException
     */
    public PageResponseDto<List<RequestLog>> list(int start, int size, String urlPattern) throws IOException {
        final File logDir = fileManager.mkTmpDir("/mock");
        final File file = new File(logDir, "info");
        if (!file.exists()){
            return new PageResponseDto<>();
        }
        final List<String> lines = FileUtils.readLines(file, StandardCharsets.UTF_8);
        List<RequestLog> requestLogs = new ArrayList<>();
        for (String line : lines) {
            if (StringUtils.isNotBlank(line)){
                RequestLog requestLog = RequestLog.deSerializer(line);
                if (StringUtils.isNotBlank(urlPattern) && urlPattern.equals(requestLog.getUrlPattern())) {
                    requestLogs.add(requestLog);
                }else if (StringUtils.isBlank(urlPattern)){
                    requestLogs.add(requestLog);
                }
            }
        }
        Collections.sort(requestLogs, (a,b) -> a.getTime().before(b.getTime()) ? 1: -1);
        final List<RequestLog> collect = requestLogs.stream().skip((start - 1) * size).limit(size).collect(Collectors.toList());
        final PageResponseDto<List<RequestLog>> tPageResponseDto = new PageResponseDto<List<RequestLog>>(collect, (long) requestLogs.size());
        return tPageResponseDto;
    }

    /**
     * 请求日志详情
     * @param id
     * @return
     */
    public RequestLogDto detail(String id) throws IOException {
        final File logDir = fileManager.mkTmpDir("/mock/requests");
        final File file = new File(logDir, id);
        final String s = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
        final RequestLogDto requestLogDto = JSON.parseObject(s, RequestLogDto.class);
        return requestLogDto;
    }

    /**
     * 记录请求日志
     * @param requestLogDto
     * @throws IOException
     */
    public void recordLog(RequestLogDto requestLogDto) throws IOException {
        // 记录请求日志
        final File logDir = fileManager.mkTmpDir("/mock/requests");
        String id = new Date().getTime()+"";
        final RequestLog requestLog = new RequestLog(requestLogDto);
        requestLog.setId(id);
        final File infoFile = new File(logDir.getParent(), "info");
        if (infoFile.exists()){
            FileUtils.writeStringToFile(infoFile,"\n"+requestLog.toSerializerString(), StandardCharsets.UTF_8,true);
        }else {
            FileUtils.writeStringToFile(infoFile,requestLog.toSerializerString(), StandardCharsets.UTF_8,true);
        }

        final String detail = JSON.toJSONString(requestLogDto);
        final File file = new File(logDir, id);
        FileUtils.writeStringToFile(file,detail, StandardCharsets.UTF_8);
    }
}
